//线路树模块
define('lineTree', ['zTree'], function () {

    var setting = {
        view: {
            showIcon: true,
            selectedMulti: false
        },
        data: {
            key: {
                name: "name"
            },
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootPId: 0
            }
        },
        callback: {
            beforeClick: function (treeId, treeNode) {
                return treeNode.type == 'LINE';
            },
            onClick: function (event, treeId, treeNode) {
                if (treeNode.id == lineTree.lineId) {
                    return;
                }
                var loadMask = $.createMask();
                setLine(treeNode);

                lineTree.nodeClick(lineTree.lineId, lineTree.dateType);
                setTimeout(function () {
                    loadMask.remove();
                }, 50);
            }
        }
    };

    var cookieLineId = $.getLineCookie(),
        cookieDateType = $.getDateTypeCookie();

    $('#dateDiv').on('click', 'a', function () {
        if (!$(this).hasClass('active')) {
            lineTree.dateType = $(this).attr('val');
            $(this).addActiveClass();
            $.setDateType(lineTree.dateType);
            lineTree.nodeClick(lineTree.lineId, lineTree.dateType);
        }
    });

    /**
     * 设置当前线路名称及ID
     * @param item ztree节点
     */
    function setLine(item) {
        lineTree.lineId = item.id;
        $("#showlineName").html("当前线路 : " + item.name);
        lineTree.lineName = item.name;
    }

    //加载完成树之后自动选中一个line节点并触发点击事件
    function autoClick(item) {
        setLine(item);
        lineTree.nodeClick(lineTree.lineId, lineTree.dateType);
    }

    /**
     * 生成线路树
     */
    function initLineTree(loadFn) {
        lineTree.nodeClick = loadFn;
        $.ajaxExt({
            async: false,
            url: "/baseOrgan/getLeftOrg4Line.htm"
        }).done(function (result) {
            if ($.isArray(result)) {
                var firstLineNode;//第一个取得的Line节点
                $.each(result, function (index, item) {

                    if (cookieLineId) {//有可能保存的cookie LineId在getLeftOrg4Line返回的数据中没有，所以需要特殊处理下
                        if (!firstLineNode && item.type == 'LINE') {
                            firstLineNode = item;
                        }
                        if (cookieLineId == item.id) {
                            autoClick(item);
                            firstLineNode = null;
                            return false;
                        }
                    } else {
                        if (item.type == 'LINE') {
                            autoClick(item);
                            return false;
                        }
                    }
                });

                if (firstLineNode) {//如果循环结束后还有值说明没有找到匹配的节点
                    autoClick(firstLineNode);
                }
                $("#lineTree").createTree(setting, result, {search: $('#lineSelected')}).expandAll(true);
            }
        });
    }

    var lineTree = {
        init: initLineTree,
        lineId: null,
        dateType: '02',
        lineName: '',
        nodeClick: $.noop
    };

    if (cookieDateType) {
        $('#dateDiv').find('a[val=' + cookieDateType + ']').addActiveClass();
        lineTree.dateType = cookieDateType;
    }

    return lineTree;
});

//驾驶行为评分热力图
define('drvBehavior', function () {

    var year = new Date().getFullYear(),//当前年份
        month = new Date().getMonth() + 1;//当前月份


    var $calendarBox = $('.calendar-box'),
        $monthBox = $('.month-box', $calendarBox),
        $daysBox = $('.table-tr6', $calendarBox),
        $evaluateBox = $('.evaluate-box', $calendarBox);


    var $dayTd = [];//日期td数组，方便对应的数据放在对应的td上面
    $monthBox.on('click', 'li', function () {
        if (!$(this).hasClass('active')) {
            month = $(this).index() + 1;
            $(this).addActiveClass();
            clearDays();
            var date = new Date(year, month - 1, 1);
            var totalDays = new Date(year, month - 1, 1).dateAdd('m', 1).dateAdd('d', -1).getDate();
            var day = date.getDay();
            var $tds;
            if (!day) {
                day = 7;
            }
            day = day - 1;
            $tds = day ? $(' tr:gt(0) td:gt(' + (day - 1) + ')', $daysBox) : $(' tr:gt(0) td', $daysBox);


            $dayTd = [];
            for (var i = 1; i <= totalDays; i++) {
                $dayTd.push($($tds[i - 1]).html(i));
            }

            currentLineId && loadData(currentLineId);
        }
    });

    //点击日期（天）
    $daysBox.on('click', 'td', function () {
        var info = $(this).data('data-info');
        if (info) {
            if (!$(this).hasClass('active') && info.avgScoreHot != 0) {
                $daysBox.find('.active').removeClass('active');
                $(this).addClass('active');
                $evaluateBox.show();
                drvChart(info, year + '年' + month + '月' + $(this).text() + '日');
            }
        }
    });

    //驾驶行为评分图表
    function drvChart(info, dateStr) {

        var score = info.avgScoreHot,
            scoreTypeId = info.scoreTypeId;
        var chartEl = document.getElementById('chart3');
        score = Number(score.toFixed(1), 10);
        var myChart = echarts.init(chartEl);
        var option = {
            title: {
                text: score,
                x: 'center',
                y: '30%',
                textStyle: {
                    color: '#fa9463',
                    fontSize: 50
                }
            },
            animation: false,
            series: [{
                type: 'pie',
                radius: ['98%', '96%'],
                silent: true,
                label: {
                    normal: {
                        show: false
                    }
                },
                data: [{
                    itemStyle: {
                        normal: {
                            color: '#faa176'
                        }
                    }
                }]
            }, {
                name: 'main',
                type: 'pie',
                radius: ['87%', '79%'],
                label: {
                    normal: {
                        show: false
                    }
                },
                data: [{
                    value: score,
                    itemStyle: {
                        normal: {
                            color: '#f9844b'
                        }
                    }
                }, {
                    value: 100 - score,
                    itemStyle: {
                        normal: {
                            color: 'transparent'
                        }
                    }
                }]
            }]
        };

        $(chartEl).siblings('h3').find('span').html(dateStr);
        var css = '';
        switch (scoreTypeId) {
            case 1:
                css = 'degree3';
                break;
            case 2:
                css = 'degree2';
                break;
        }
        $(chartEl).siblings('h4').attr('class', css).html(info.scoreType);
        myChart.setOption(option);
    }

    $daysBox.on('click', 'td', function () {

        if ($(this).val()) {

        }
    });

    function clearDays() {
        $(' tr:gt(0) td', $daysBox).html('').attr('class', '').removeData('data-info');
    }

    function clearAll() {
        $('.active', $monthBox).removeClass('active');
        clearDays();
        $evaluateBox.hide();
    }

    //上一年
    var $yearSpan = $('.prev', $calendarBox).on('click', function () {
        year--;
        $yearSpan.html(year + '年');
        clearAll();
    }).next().html(year + '年');

    //下一年
    $('.next', $calendarBox).on('click', function () {
        if (year == new Date().getFullYear()) {
            return;
        }
        year++;
        $yearSpan.html(year + '年');
        clearAll();
    });

    function setDays(month) {

        if (month) {
            var begin = new Date(year, month - 1, 1),
                end = begin.dateAdd('m', 1).dateAdd('d', -1);
        }
    }

    var $flag = $('#rlt-type-flag');//驾驶行为评分热力图flag配置区域

    function loadData() {
        $.ajaxExt({
            url: '/driverBehavior/statScoreHot.htm',
            data: {
                lineId: currentLineId,
                monthly: year + '-' + (month < 10 ? "0" + month : month)
            },
            success: function (obj) {

                if (obj.scoreHotList) {
                    var data = obj.scoreHotList;
                    data && $.each(data, function (i, item) {
                        var $td = $dayTd[i];
                        if (item.scoreTypeId == 1) {//待改进
                            if (item.avgScoreHot == 0) {
                                $td.addClass('degree1');
                            } else {
                                $td.addClass('degree3');
                            }
                        } else if (item.scoreTypeId == 2) {//一般
                            $td.addClass('degree2');
                        }
                        $td.data('data-info', item);
                        if (i == 0) {
                            $td.trigger('click');
                        }
                    });
                }

                if (obj.levelList) {
                    $.each(obj.levelList, function (i, item) {
                        $flag.find('span').eq(i).html(item.scoreType);
                    })
                }

            }
        })
    }

    $monthBox.find('li').eq(month - 1).trigger('click');

    var currentLineId;//保存当前选择的线路ID，以免切换时间类型的时候也触发loadData方法
    return {
        loadData: function (lineId) {
            if (lineId == currentLineId) {
                return;
            }
            currentLineId = lineId;
            loadData(lineId);
        }
    }
});

//驾驶行为分类占比
function chart1(dateType, lineId) {

    var myChart = echarts.init(document.getElementById('chart1'));

    $.ajaxExt({
        url: '/driverBehavior/statBeorRatioRange.htm',
        data: {
            dateType: dateType,
            lineId: lineId
        },
        success: function (data) {

            if (data) {
                var clusTypeRange0 = data.rangeVo.clusTypeRange0,
                    clusTypeRange1 = data.rangeVo.clusTypeRange1,
                    clusTypeRange2 = data.rangeVo.clusTypeRange2;
                var option = {
                    title: {
                        text: '驾驶员行为分类占比',
                        x: 'center',
                        padding: 15,
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    legend: {
                        orient: 'vertical',
                        bottom: '50%',
                        right: '5%',
                        formatter: function (name) {
                            var txt = name + ' ';
                            if (name == '好') {
                                txt += (clusTypeRange0 > 0 ? '↑ ' : '↓ ') + clusTypeRange0 + '%';
                            } else if (name == '中') {
                                txt += (clusTypeRange2 > 0 ? '↑ ' : '↓ ') + clusTypeRange2 + '%';
                            } else {
                                txt += (clusTypeRange1 > 0 ? '↑ ' : '↓ ') + clusTypeRange1 + '%';
                            }
                            return txt;
                        },
                        data: [
                            {
                                name: '好',
                                textStyle: {
                                    color: '#2cd282'
                                }
                            },
                            {
                                name: '中',
                                textStyle: {
                                    color: '#f9ad3f'
                                }
                            },
                            {
                                name: '差',
                                textStyle: {
                                    color: '#ff6060'
                                }
                            }
                        ]
                    },
                    series: [
                        {
                            name: '当期占比',
                            type: 'pie',
                            radius: '65%',
                            label: {
                                normal: {
                                    formatter: '{b}: {d} %'
                                }
                            },
                            data: [
                                {
                                    value: data.beorRaCurrent.clusType0, name: '好', itemStyle: {
                                    normal: {color: '#2cd282'}
                                }
                                },
                                {
                                    value: data.beorRaCurrent.clusType2, name: '中', itemStyle: {
                                    normal: {color: '#f9ad3f'}
                                }
                                },
                                {
                                    value: data.beorRaCurrent.clusType1, name: '差', itemStyle: {
                                    normal: {color: '#ff6060'}
                                }
                                }
                            ]
                        }
                    ]
                };

                myChart.setOption(option);
            } else {
                myChart.clear();
            }
        }
    });

}

//驾驶员评分概览
function chart2(dateType, lineId) {

    var myChart = echarts.init(document.getElementById('chart2'));


    $.ajaxExt({
        url: '/driverBehavior/statScoreLevelRatio.htm',
        data: {
            dateType: dateType,
            lineId: lineId
        },
        success: function (data) {
            if (data && (data.scoreRatioVo || data.scoreLevelVo)) {

                var makeLine20 = data.scorePointVo.pointScore - 60 ? parseFloat(((data.scorePointVo.pointScore - 60) * 100 / 40).toFixed(1)) : 10;
                if (makeLine20 < 10) {
                    makeLine20 = 10;
                }
                makeLine20 = makeLine20 + '%';
                var option = {
                    "title": {
                        "text": "驾驶员评分概览",
                        x: 'center',
                        padding: 15,
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    "tooltip": {
                        "trigger": "axis",
                        "axisPointer": {
                            "type": "shadow",
                            textStyle: {
                                color: "#fff"
                            }

                        },
                        formatter: function (params) {
                            var text = '';
                            params && $.each(params, function (i, item) {
                                if (i == 0) {
                                    text += item.name + '-' + (item.name + 5) + ':<br/>';
                                }
                                if (i == 0) {
                                    text += item.seriesName + ':' + item.data + '<br/>';
                                }
                                if (i == 1) {
                                    text += item.seriesName + ':' + item.data + '%';
                                }
                            });
                            return text;
                        }
                    },
                    "grid": {
                        "borderWidth": 0,
                        "top": 110,
                        "bottom": 95,
                        textStyle: {
                            color: "#fff"
                        }
                    },
                    "legend": {
                        x: 'center',
                        bottom: 0,
                        selectedMode: false,
                        selected: {
                            '驾驶员平均分': false,
                            '20%后进分割线': true
                        },
                        textStyle: {
                            color: '#90979c'
                        },
                        inactiveColor: '#ff6060',
                        "data": ['驾驶员数量', '数量百分比', '驾驶员平均分', {
                            name: '20%后进分割线',
                            icon: 'rect',
                            textStyle: {
                                color: '#f9ad3f'
                            }
                        }]
                    },

                    "xAxis": [{
                        "type": "category",
                        "axisLine": {
                            lineStyle: {
                                color: '#90979c'
                            }
                        },
                        "splitLine": {
                            "show": false
                        },
                        "axisTick": {
                            "show": true
                        },
                        "splitArea": {
                            "show": false
                        },
                        "axisLabel": {
                            show: true,
                            formatter: function (value, index) {
                                return value + '-' + (value + 5);
                            },
                            "interval": 0

                        },
                        data: [60, 65, 70, 75, 80, 85, 90, 95, 100]
                    }],
                    "yAxis": [{
                        "type": "value",
                        "splitLine": {
                            "show": false
                        },
                        "axisLine": {
                            lineStyle: {
                                color: '#90979c'
                            }
                        },
                        "axisTick": {
                            "show": false
                        },
                        "axisLabel": {
                            "interval": 0

                        },
                        "splitArea": {
                            "show": false
                        }

                    }, {
                        "type": "value",
                        "splitLine": {
                            "show": false
                        },
                        "axisLine": {
                            lineStyle: {
                                color: '#90979c'
                            }
                        },
                        "axisTick": {
                            "show": false
                        },
                        "axisLabel": {
                            "interval": 0,
                            formatter: function (value, index) {
                                return value + '%';
                            }

                        },
                        "splitArea": {
                            "show": false
                        }

                    }],
                    "series": [{
                        "name": "驾驶员数量",
                        "type": "bar",
                        barWidth: '100%',
                        barMaxWidth: '100%',
                        "itemStyle": {
                            "normal": {
                                "color": "#2cd282"
                            }
                        },
                        markLine: {
                            label: {
                                normal: {
                                    textStyle: {
                                        color: '#fff'
                                    }
                                }
                            },
                            lineStyle: {
                                normal: {
                                    type: 'solid',
                                    color: '#ff6060'
                                }
                            },
                            data: data.scorePointVo ? [//平均分

                                [{
                                    name: data.scoreAvgVo.avgScore,
                                    x: data.scoreAvgVo.avgScore - 60 ? ((data.scoreAvgVo.avgScore - 60) * 100 / 40).toFixed(1) + '%' : '0%',
                                    y: '75%'
                                }, {
                                    x: data.scoreAvgVo.avgScore - 60 ? ((data.scoreAvgVo.avgScore - 60) * 100 / 40).toFixed(1) + '%' : '0%',
                                    y: '25%'
                                }]
                            ] : []
                        },
                        "data": data.scoreLevelVo ? [
                            data.scoreLevelVo.scoreLevel1,
                            data.scoreLevelVo.scoreLevel2,
                            data.scoreLevelVo.scoreLevel3,
                            data.scoreLevelVo.scoreLevel4,
                            data.scoreLevelVo.scoreLevel5,
                            data.scoreLevelVo.scoreLevel6,
                            data.scoreLevelVo.scoreLevel7,
                            data.scoreLevelVo.scoreLevel8
                        ] : []
                    }, {
                        "name": "数量百分比",
                        "type": "line",
                        symbolSize: 10,
                        symbol: 'circle',
                        yAxisIndex: 1,
                        "itemStyle": {
                            "normal": {
                                "color": "#fce630",
                                "barBorderRadius": 0
                            }
                        },
                        markLine: {
                            label: {
                                normal: {
                                    textStyle: {
                                        color: '#fff'
                                    }
                                }
                            },
                            lineStyle: {
                                normal: {
                                    type: 'solid',
                                    color: '#f9ad3f'
                                }
                            },
                            data: data.scorePointVo ? [
                                [{
                                    name: data.scorePointVo.pointScore,
                                    x: makeLine20,
                                    y: '75%'
                                }, {
                                    x: makeLine20,
                                    y: '25%'
                                }]
                            ] : []
                        },
                        "data": data.scoreRatioVo ? [
                            data.scoreRatioVo.scoreRatio1,
                            data.scoreRatioVo.scoreRatio2,
                            data.scoreRatioVo.scoreRatio3,
                            data.scoreRatioVo.scoreRatio4,
                            data.scoreRatioVo.scoreRatio5,
                            data.scoreRatioVo.scoreRatio6,
                            data.scoreRatioVo.scoreRatio7,
                            data.scoreRatioVo.scoreRatio8
                        ] : []
                    }, {
                        "name": "驾驶员平均分",
                        "type": "bar",
                        "data": [null]
                    }, {
                        "name": "20%后进分割线",
                        "type": "line",
                        "itemStyle": {
                            "normal": {
                                "color": "#f9ad3f"
                            }
                        },
                        "data": [null]
                    }]
                };

                myChart.setOption(option);
            } else {
                myChart.clear();
            }
        }
    });

}

//单个驾驶员行为分析
define('oneDrvBehavior', function () {
    var $select = $('#drv-select').on('change', function () {
        if (this.value && this.value != currentDrvId) {
            currentDrvId = this.value;
            currentDrvName = $(this).find('option:selected').text();
            loadAllData();
        }
    });

    var currentLineId, currentDateType, currentDrvId, currentDrvName;
    //加载驾驶员
    function loadDrv(lineId) {

        $.ajaxExt({
            url: '/driverBehavior/getDrvList.htm',
            data: {
                lineId: lineId
            },
            success: function (data) {
                $select.empty();
                data && $.each(data, function (i, drv) {
                    $select.append('<option value="{0}">{1}</option>'.format(drv.drvId, drv.drvName));
                    i == 0 && (currentDrvId = drv.drvId);
                    currentDrvName = drv.drvName;
                });
                $select.select2();
                if (data && data.length) {
                    toggleShow('show');
                    loadAllData();
                } else {
                    toggleShow('hide');
                    currentDrvId = null;
                    currentDrvName = null;
                }
            }
        });
    }

    //请求所以的相关数据
    function loadAllData() {
        drvScoreChart();
        creatHx();
        khpfzs();
    }

    var $chartArea = $('#chart5-area');

    //切换显示隐藏单个驾驶员行为分析（驾驶员列表可能为空）
    function toggleShow(method) {
        var $area = $('#dgjsyxwfx');
        if (method == 'show') {
            $area.show();
        } else if (method == 'hide' && $area.is(':visible')) {
            $area.hide();
        }
    }

    //考核评分
    function drvScoreChart() {
        $.ajaxExt({
            url: '/driverBehavior/getDrvScoreSortSingle.htm',
            data: {
                dateType: currentDateType,
                lineId: currentLineId,
                drvId: currentDrvId
            },
            success: function (data) {
                if (data) {
                    if (data.score) {
                        data.score = data.score.toFixed(0);
                    }
                    $('#scoreGth').html(data.scoreGth > 0 ? (data.scoreGth + '↑') : ((data.scoreGth || 0) + '↓'));
                } else {
                    data = {};
                    $('#scoreGth').html("");
                }
                $chartArea.setViewData(data);
                data = data || {};
                createScoreChart(data.score);
            }
        });
    }

    //考核评分图表
    function createScoreChart(score) {
        var chartEl = document.getElementById('chart5');
        var myChart = echarts.init(chartEl);
        var option = {
            tooltip: {
                formatter: "考核评分: {c}"
            },
            series: [
                {
                    name: '考核评分',
                    type: 'gauge',
                    radius: '95%',
                    detail: {show: false},
                    data: [{value: score || 0, name: ''}]
                }
            ]
        };
        myChart.setOption(option);
    }

    //行为画像
    var $hxArea = $('#hx-area').empty();
    $hxArea.on('click', '.item', function () {
        var featureType = $(this).attr('data-featureType');
        getBehaviorFeatureDetail(featureType);
    });
    function creatHx() {
        $hxArea.empty();
        $.ajaxExt({
            url: '/driverBehavior/getBehaviorFeatureTypeSingle.htm',
            data: {
                dateType: currentDateType,
                lineId: currentLineId,
                drvId: currentDrvId
            },
            success: function (data) {
                if (data) {
                    $.each(data, function (i, item) {
                        if (i < 7) {
                            var css = '';
                            switch (item.featureImporType) {
                            	case '正常':
                                    css = 'degree1';
                                    break;
                                case '一般':
                                    css = 'degree2';
                                    break;
                                case '严重':
                                    css = 'degree3';
                                    break;
                            }
                            var text = item.featureTypeDes;
                            if (text.length != 2) {

                                var begin = text.length > 4 ? 3 : 2;
                                text = text.substr(0, begin) + '<br/>' + text.substr(begin, text.length - begin + 2);
                            }
                            $hxArea.append('<div class="item item{0} {1}" data-featureType="{2}">{3}</div>'.format(i + 1, css, item.featureType, text));
                        }
                    });
                }
            }
        })
    }

    //考核评分走势
    function khpfzs() {

        var chartEl = document.getElementById('chart6');
        var myChart = echarts.init(chartEl);

        weekChart();
        $.ajaxExt({
            url: '/driverBehavior/getBehaviorScoreTrend.htm',
            data: {
                dateType: currentDateType,
                lineId: currentLineId,
                drvId: currentDrvId
            },
            success: function (data) {
                if (data && data.length) {
                    var xAxis = [],
                        seriesData = [];
                    $.each(data, function (i, item) {
                        xAxis.push(item.dateNum);
                        seriesData.push(item.avgScore);
                    });
                    var option = {
                        title: {
                            text: '考核评分走势',
                            x: 'center',
                            textStyle: {
                                color: '#43535b',
                                fontSize: 14
                            }
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        grid: {
                            right: '20%'
                        },
                        xAxis: [{
                            type: 'category',
                            axisTick: {
                                alignWithLabel: true
                            },
                            data: xAxis
                        }],
                        yAxis: [{
                            type: 'value',
                            name: '分'
                        }],
                        series: [{
                            name: '分数',
                            type: 'line',
                            data: seriesData
                        }]
                    };

                    myChart.on('click', function (param) {
                        var name = param.name;
                        if (name.length == 10) {
                            weekChart(name);
                        }
                    });

                    myChart.setOption(option);
                } else {
                    myChart.clear();
                }
            }
        });

        //一周考核评分雷达图
        function weekChart(date) {
            var el2 = document.getElementById('chart7');
            var chart2 = echarts.init(el2);

            if (date) {

                $.ajaxExt({
                    url: '/driverBehavior/getBehaviorScoreWeek.htm',
                    data: {
                        endTime: date,
                        lineId: currentLineId,
                        drvId: currentDrvId
                    },
                    success: function (weekData) {
                        if (weekData && weekData.length) {

                            var xAxis = [],
                                seriesData = [];
                            $.each(weekData, function (i, item) {
                                xAxis.push({name: item.dateNum, max: 100});
                                seriesData.push(item.avgScore);
                            });
                            var option = {
                                title: {
                                    text: '一周考核评分雷达图',
                                    x: 'center',
                                    textStyle: {
                                        color: '#43535b',
                                        fontSize: 14
                                    }
                                },
                                tooltip: {},
                                radar: {
                                    indicator: xAxis
                                },
                                series: [{
                                    name: '分数',
                                    type: 'radar',
                                    data: [
                                        {
                                            value: seriesData
                                        }
                                    ]
                                }]
                            };

                            chart2.setOption(option);
                        } else {
                            chart2.clear();
                        }
                    }
                });
            } else {
                chart2.clear();
            }
        }
    }

    //驾驶员行为画像点击行为类型弹窗
    var $modal = $('#behaviorDetail-modal');

    function getBehaviorFeatureDetail(featureType) {
        var $table = $('table', $modal);
        $('tr:gt(0)', $table).remove();
        $.ajaxExt({
            url: '/driverBehavior/getBehaviorFeatureDetail.htm',
            loadMask: true,
            data: {
                dateType: currentDateType,
                lineId: currentLineId,
                drvId: currentDrvId,
                featureType: featureType
            },
            success: function (feInfos) {
                if (feInfos && feInfos.length) {
                    $(".site-body").removeClass("overflow-a");
                    $modal.show();
                    $.each(feInfos, function (i, item) {
                        var css = 'degree2';
                        if (item.featureEvalT == 0) {
                            css = 'degree3';
                        } else if (i.featureEvalT == 1) {
                            css = 'degree1';
                        }
                        var str = '<tr><td>{0}</td><td class="ac {1}">{2}</td><td class="ac">{3}</td><td class="ac"><a>查看</a></td><td>{4}</td></tr>';
                        var $tr = $(str.format(item.featureDes, css, item.featureEval, item.featureImpor, item.featureImpr)).appendTo($table);
                        $tr.data('data-info', item);
                    });
                    $modal.find(".mask-bg").height($table.height()+200);
                } else {
                    $.messager.alert("提示", "无数据");
                }
            }
        })
    }

    $modal.on('click.view', 'tr a', function () {

        var info = $(this).closest('tr').data('data-info');
        var chartEl = document.getElementById('chart8');
        var myChart = echarts.init(chartEl);
        $.ajaxExt({
            url: '/driverBehavior/getBehaviorFeatureCompare.htm',
            data: {
                dateType: currentDateType,
                lineId: currentLineId,
                drvId: currentDrvId,
                feature: info.feature
            },
            loadMask: true,
            success: function (data) {
                if (data && data.distFitX) {
                    $('#chart8-parent').show();
                    var goodArr = [],
                        badArr = [],
                        drvArr = [];
                    data.goodDistFit && $.each(data.goodDistFit, function (i, item) {
                        goodArr.push([parseFloat(data.distFitX[i]), parseFloat(item)]);
                    });
                    data.badDistFit && $.each(data.badDistFit, function (i, item) {
                        badArr.push([parseFloat(data.distFitX[i]), parseFloat(item)]);
                    });
                    data.drvFitDist && $.each(data.drvFitDist, function (i, item) {
                        drvArr.push([parseFloat(data.distFitX[i]), parseFloat(item)]);
                    });
                    var option = {
                        title: {
                            text: info.featureDes,
                            x: 'center',
                            padding: 15,
                            textStyle: {
                                fontSize: 14
                            }

                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                            }
                        },
                        legend: {
                            bottom: '0%',
                            data: [
                                {
                                    name: '好',
                                    icon: 'rect'
                                },
                                {
                                    name: '差',
                                    icon: 'rect'
                                },
                                {
                                    name: currentDrvName,
                                    icon: 'rect'
                                }
                            ]
                        },
                        xAxis: [{
                            type: 'value'
                        }],
                        yAxis: [{
                            type: 'value'
                        }],
                        series: [{
                            name: '好',
                            type: 'line',
                            itemStyle: {
                                normal: {
                                    color: '#2cd282'
                                }
                            },
                            showSymbol: false,
                            data: goodArr
                        }, {
                            name: '差',
                            type: 'line',
                            itemStyle: {
                                normal: {
                                    color: '#ff6060'
                                }
                            },
                            showSymbol: false,
                            data: badArr
                        }, {
                            name: currentDrvName,
                            type: 'line',
                            itemStyle: {
                                normal: {
                                    color: '#1ac1fe'
                                }
                            },
                            showSymbol: false,
                            data: drvArr
                        }]
                    };
                    myChart.setOption(option);
                } else {
                    $.messager.alert("提示", "无数据");
                    myChart.clear();
                }
            }
        })
    });

    //打印行为报告界面
    var printWin;
    $('#print').on('click', function () {
        report('./report/dataAnalysis/driverBehaviorReport.htm?dateType={0}&lineId={1}&drvId={2}'.format(currentDateType, currentLineId, currentDrvId));
    });
    function report(src) {
        if (printWin) {
            printWin[0].src = src;
            printWin.dialog('open');
        } else {
            printWin = $('<div>').dialog({
                title: '驾驶员行为分析报告',
                url: src,
                height: $(window.parent.document).height() * 0.9,
                width: 885,
                autoOpen: true,
                buttons: [
                    {
                        text: '打印',
                        css: 'mr10',
                        click: function () {
                            this.contentWindow.print();
                        }
                    }
                ]
            });
        }
    }

    return {
        loadData: function (dateType, lineId) {
            if (currentDateType == dateType && currentLineId == lineId) {
                return;
            }
            var lineIdChanged = currentLineId != lineId;//线路ID是否更改了
            currentDateType = dateType;
            currentLineId = lineId;
            if (lineIdChanged) {

                loadDrv(lineId);
            } else {
                loadAllData();
            }
        }
    }
});

require(['zTree', 'lineTree', 'drvBehavior', 'echarts3', 'oneDrvBehavior', 'select2'], function (_z, lineTree, drvBehavior, echarts, oneDrvBehavior) {
    window.echarts = echarts;

    lineTree.init(function (lineId, dateType) {
        $.setCurrentLine(lineId);
        oneDrvBehavior.loadData(dateType, lineId);
        loadData(dateType, lineId);
        drvBehavior.loadData(lineId);
    });


    function loadData(dateType, lineId) {
        chart1(dateType, lineId);
        chart2(dateType, lineId);
        getDrvScoreSortList(lineId, dateType);
        statBehaviorFeature(lineId, dateType);
    }

    //进步/退步
    var $jbTbModel = $('#jb-tb-modal');
    $('#tb-jb').on('click', function () {

        $.ajaxExt({
            url: '/driverBehavior/getDrvImproveList.htm',
            loadMask: true,
            data: {
                dateType: lineTree.dateType,
                lineId: lineTree.lineId
            },
            success: function (data) {
                $('tr:gt(0)', $jbTbModel).remove();
                $jbTbModel.show();
                if (data && (data.dataListPro || data.dataListPro)) {
                    //进步
                    data.dataListPro && $.each(data.dataListPro, function (i, item) {
                        var $tr = $('<tr></tr>');
                        $tr.append('<td class="ac border-r0">{0}{1}</td>'.format(i < 3 ? ('<img src="../../content/images/driver-rank' + (i + 1) + '.png" width="15" height="20" class="mr10 vm">') : '', item.drvName));
                        $tr.append('<td class="ac degree1 ">{0} ↑</td>'.format(item.impDes))
                        $('table', $jbTbModel).append($tr);
                    });

                    //退步
                    data.dataListBac && $.each(data.dataListBac, function (i, item) {
                        var $tr = $('table tr', $jbTbModel).get(i + 1);
                        if ($tr) {
                            $tr = $($tr);
                        } else {
                            $tr = $('<tr></tr>').appendTo($('table', $jbTbModel));
                        }

                        $tr.append('<td class="ac border-r0">{0}</td>'.format(item.drvName));
                        $tr.append('<td class="ac degree3"><a>{0} ↓</a></td>'.format(item.impDes));
                    });
                } else {
                    $.messager.alert('提示', '无数据！')
                }
            }
        })
    });


    //全部排名
    $('#wholeSafeRank').on('click', function () {
        loadPmByPage(1);
    });
    var $pmModal = $('#pm-fy-modal');
    var $pmPage = $('#pm-page');

    function loadPmByPage(rowNum) {
        var $table = $('table', $pmModal);
        $('tr:gt(0)', $table).remove();
        $.ajaxExt({
            url: '/driverBehavior/getDrvScoreSortPage.htm',
            data: {
                page: rowNum,
                row: 10,
                dateType: lineTree.dateType,
                lineId: lineTree.lineId
            },
            success: function (obj) {
                if (obj && obj.total) {
                    $pmModal.show();
                    $pmPage.unbind().empty();
                    $.each(obj.data, function (i, item) {

                        $table.append('<tr><td class="ac"><span class="rank-num">{rowNum}</span></td><td class="ac">{drvName}</td><td class="ac">{goodRate}%</td><td class="ac">{midRate}%</td><td>{badRate}%</td><td class="ac"><span class="score-num">{score}</span></td></tr>'.format(item));
                    });
                    $pmPage.createPage({
                        pageCount: obj.pageTotal,
                        current: obj.rowBounds.pageNumber,
                        backFn: function (p) {
                            loadPmByPage(p);
                        }
                    });
                } else {
                    if (rowNum == 1) {
                        $.messager.alert("提示", '无数据');
                    }
                }
            }
        });
    }

    $('#pm10-table').on('dblclick', 'tr', function () {
        var drvId = $(this).data('data-drvId');
        if (drvId) {
            $('#drv-select').select2('val', drvId).trigger('change');
        }
    });

});

//驾驶员排名前10
function getDrvScoreSortList(lineId, dateType) {
    var $table = $('#pm10-table'),
        $info = $('#pm10-table-info').html('');
    $('td', $table).not('.good-td,.bad-td').html('');
    $('tr', $table).removeData();
    $.ajaxExt({
        url: '/driverBehavior/getDrvScoreSortList.htm',
        data: {
            lineId: lineId,
            dateType: dateType
        },
        success: function (data) {

            var $tr = $('tr:gt(0)', $table);
            //前5
            if (data && data.dataListAsc && data.dataListAsc.length) {
                $.each(data.dataListAsc, function (i, item) {
                    var _$tr = $tr[i],
                        _$td;
                    if (i == 0) {
                        _$td = $('td:gt(0)', _$tr);
                    } else {
                        _$td = $('td', _$tr);
                    }
                    _$td[0].innerHTML = item.rowNum;
                    _$td[1].innerHTML = item.drvName;
                    _$td[2].innerHTML = item.goodRate + '%';
                    _$td[3].innerHTML = item.midRate + '%';
                    _$td[4].innerHTML = item.badRate + '%';
                    _$td[5].innerHTML = item.score;
                    $(_$tr).data('data-drvId', item.drvId);
                });
            }

            //后5
            if (data && data.dataListDesc && data.dataListDesc.length) {
                $.each(data.dataListDesc, function (i, item) {
                    var _$tr = $tr[i + 5],
                        _$td;
                    if (i == 0) {
                        _$td = $('td:gt(0)', _$tr);
                    } else {
                        _$td = $('td', _$tr);
                    }
                    _$td[0].innerHTML = item.rowNum;
                    _$td[1].innerHTML = item.drvName;
                    _$td[2].innerHTML = item.goodRate + '%';
                    _$td[3].innerHTML = item.midRate + '%';
                    _$td[4].innerHTML = item.badRate + '%';
                    _$td[5].innerHTML = item.score;
                    $(_$tr).data('data-drvId', item.drvId);
                });
            }

            $info.html(data.timeRangeVo ? '({0}至{1})'.format(data.timeRangeVo.rangeFrom, data.timeRangeVo.rangeTo) : '');
        }
    })
}

//待改进驾驶行为排名前10
function statBehaviorFeature(lineId, dateType) {
    var chartEl = document.getElementById('chart4');

    var myChart = echarts.init(chartEl);
    $.ajaxExt({
        url: '/driverBehavior/statBehaviorFeature.htm',
        data: {
            lineId: lineId,
            dateType: dateType
        },
        success: function (data) {
            if (data && data.length) {
                var xArr = [],
                    yArr = [];
                $.each(data, function (i, item) {
                    yArr.push(item.featureDes);
                    xArr.push(item.avgImp);
                });
                var option = {
                    xAxis: {
                        name: '严重度',
                        nameTextStyle: {
                            color: '#454545'
                        }
                    },
                    grid: {
                        left: 250
                    },
                    tooltip: {},
                    yAxis: [{
                        inverse: true,
                        data: yArr
                    }],
                    series: [{
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                color: '#27b3e8'
                            }
                        },
                        data: xArr
                    }]
                };
                myChart.setOption(option);
            } else {
                myChart.clear();
            }
        }
    })
}